<template>
  <div class="default-main ba-table-box">
    <el-alert class="ba-table-alert"
              v-if="baTable.table.remark"
              :title="baTable.table.remark"
              type="info"
              show-icon />

    <!-- 表格顶部菜单 -->
    <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                 :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
      <template #orderId>
        <el-input v-model="baTable.comSearch.form['order_id']"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入订单号" />
      </template>
    </TableHeader>

    <template style="display: block; margin: 10px 0;">
      <el-row :gutter="10"
              class="mb8">
        <el-col :span="1.5"
                v-if="baTable.auth('endShipping')">
          <el-button type="danger"
                     @click="endShippingOperate">
            <Icon :color="'#ffffff'"
                  name="el-icon-CirclePlusFilled" />已处理
          </el-button>
        </el-col>
        <el-col :span="3"
                v-if="baTable.auth('automaticShipping')">
          <el-select v-model="state.overseas_warehouse"
                     clearable
                     placeholder="请选择海外仓">
            <el-option v-for="item in state.overseas_warehouse_arr"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
              <span style="float: left">{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('automaticShipping')">
          <el-button type="primary"
                     @click="automaticShippingOperate">自动发货</el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('export')">
          <el-button type="warning"
                     @click="exportExcelOperate"
                     :loading="state.buttonLoading">
            <Icon :color="'#ffffff'"
                  name="el-icon-Position" />导出
          </el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('markerOrder')">
          <el-button type="danger"
                     @click="markerOrderOperate">暂无渠道发货</el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('uploadOrder')">
          <el-upload ref="upload"
                     class="upload-demo"
                     action=""
                     :show-file-list="false"
                     @change="onOrderUpload"
                     :auto-upload="false">
            <template #trigger>
              <el-button type="primary">上传网红订单</el-button>
            </template>
            <el-link style="color: #ffffff;"
                     :href="`${baseUrl}/storage/system/orderwh.xls`"
                     :underline="false">
              <el-button type="warning"
                         style="margin-left: 10px;vertical-align: initial;">
                下载网红订单
              </el-button>
            </el-link>
          </el-upload>
        </el-col>
      </el-row>
    </template>

    <el-tabs v-model="activeName"
             class="demo-tabs"
             @tab-click="handleStatus"
             type="border-card">
      <el-tab-pane label="全部"
                   name=""></el-tab-pane>
      <el-tab-pane label="等待发货"
                   name="0"></el-tab-pane>
      <el-tab-pane label="排队发货中"
                   name="1"></el-tab-pane>
      <el-tab-pane label="发货异常"
                   name="2"></el-tab-pane>
      <el-tab-pane label="等待海外仓跟踪号"
                   name="3"></el-tab-pane>
      <el-tab-pane label="发货成功"
                   name="4"></el-tab-pane>
      <el-tab-pane label="暂无渠道发货"
                   name="6"></el-tab-pane>
    </el-tabs>
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table />

    <!-- 表单 -->
    <PopupForm />
  </div>
</template>


<script setup lang="ts">
import { onBeforeMount, provide, reactive, ref } from 'vue'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi, fileDownload } from '/@/api/common'
import { useAdminInfo } from '/@/stores/adminInfo'
import { useI18n } from 'vue-i18n'
import {ElMessageBox, ElMessage , type TabsPaneContext } from 'element-plus'
import { automaticShipping, exportExcel, markerOrder, fileUpload, endShipping } from '/@/api/backend/order/orderWh'
import {  getWareHouseList } from '/@/api/backend/order/order'
import Cookies from 'js-cookie'
import { getUrl } from '/@/utils/axios'

defineOptions({
    name: 'order/orderWh',
})

const { t } = useI18n()
const baseUrl = getUrl()
const adminInfo = useAdminInfo()
const activeName = ref('');
const state: {
    overseas_warehouse:string,
    overseas_warehouse_arr: Array<any>,
    buttonLoading: boolean
} = reactive({
    overseas_warehouse:'',
    overseas_warehouse_arr: [],
    buttonLoading: false,
})

const optButtons = defaultOptButtons(['edit', 'delete'])
optButtons[1].display = (row) => {
    return row.id != adminInfo.id
}


const baTable = new baTableClass(
    new baTableApi('/order/orderWh/'),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            // { label: t('order.orderWh.order_id'), prop: 'order_id', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            {
                label: '订单号',
                prop:  'order_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                align: 'center',
                comSearchSlotName: 'orderId'
            },
            { label: t('order.orderWh.skuinfo'), prop: 'skuinfo', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: t('order.orderWh.tracking_number'), prop: 'tracking_number', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query')  },
            { label: t('order.orderWh.buyer_name'), prop: 'name', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { 
                label: t('order.orderWh.status'), 
                prop: 'tracking_beforehand', 
                operator: false,
                align: 'center', 
                render: 'tag',
                replaceValue: {
                    '0': t('order.orderWh.waiting_delivery'),
                    '1': t('order.orderWh.queuing_delivery'), 
                    '2': t('order.orderWh.delivery_error'),
                    '3': t('order.orderWh.AWAITING_OVERSEAS_NO'),
                    '4': t('order.orderWh.delivery_success'),
                    '5': t('order.orderWh.COMPLETED'),
                    '6': t('order.orderWh.No_channel_delivery'),
                    },
                width: '140'
            },
             { label: t('order.orderWh.Create time'), prop: 'createtime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
             { label: '发货时间', prop: 'sendTime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { 
                label: t('order.orderWh.warehouse_name'), 
                prop: 'warehouse_name', 
                align: 'center', 
                render: 'tag',
                operator: false
            },
           
            { label: t('order.orderWh.ship_msg'), prop: 'msg', align: 'center', operator: false },
            
            
            {
                label: t('Operate'),
                align: 'center',
                width: '100',
                render: 'buttons',
                buttons: optButtons,
                operator: false,
            },
        ],
        dblClickNotEditColumn: ['all']
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

const handleStatus = (tab: TabsPaneContext) => {
    // baTable.filter = {'status': tab.props.name}
    baTable.comSearch.form['status'] = tab.props.name
    const comSearchData: Array<any> = baTable.table.filter?.search || [];
    comSearchData.push({
        field: "status",
        val: tab.props.name,
        operator: "",
        render: "",
    })
    baTable.onTableAction('com-search', comSearchData)
}

const automaticShippingOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择需要发货的订单',
        })
        return
    }

    // console.log(99999, ids, overseas_warehouse.value, golden_ant.value);
    // return
    const params = { ids: ids, warehouse_id: state.overseas_warehouse}
    automaticShipping('post', params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const markerOrderOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择需要发货的订单',
        })
        return
    }

    const params = { ids: ids}
    markerOrder('post', params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}

const endShippingOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择订单',
        })
        return
    }
    const status = activeName.value
    const params = { ids: ids, status: '5'}
    endShipping(params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}

//上传刷单文件
const onOrderUpload = (file: any) => {
    let fd = new FormData()
    fd.append('file', file.raw)
    fileUpload(fd).then((res) => {
        if (res.code == 200) {
            ElMessage ({
                type: 'success',
                message: res.msg,
            })
        } else {
            ElMessage ({
                type: 'error',
                message: '刷单上传失败',
            })
        }
    })
}

const getOverseasWarehouseArr = () => {
    return getWareHouseList().then(res => {
        if(res.data && res.data.length) {
            state.overseas_warehouse_arr = res.data.map((v: any) => {
                return {
                    label: v.warehouse_name,
                    value: v.warehouse_id
                }
            })
            state.overseas_warehouse = state.overseas_warehouse_arr[0].value
        } else {
            state.overseas_warehouse = ''
            state.overseas_warehouse_arr = []
        }
    })
}

onBeforeMount(async () => {
    await getOverseasWarehouseArr()
})

</script>

<style scoped lang="scss"></style>
